$(document).ready(function(){
        $("#up-img-touch").click(function(){
        		  $("#doc-modal-1").modal({width:'600px'});
        });
});

$(function() {
    'use strict';
    // 初始化
    var $image = $('#image');
    $image.cropper({
        aspectRatio: '1',
        autoCropArea:0.8,
        preview: '.up-pre-after',

    });

    // 事件代理绑定事件
    $('.docs-buttons').on('click', '[data-method]', function() {
   
        var $this = $(this);
        var data = $this.data();
        var result = $image.cropper(data.method, data.option, data.secondOption);
        switch (data.method) {
            case 'getCroppedCanvas':
            if (result) {
                // 显示 Modal
                $('#cropped-modal').modal().find('.am-modal-bd').html(result);
                $('#download').attr('href', result.toDataURL('image/jpeg'));
            }
            break;
        }
    });
    
    

    // 上传图片
    var $inputImage = $('#inputImage');
    var URL = window.URL || window.webkitURL;
    var blobURL;

    if (URL) {

        $inputImage.change(function () {
            var files = this.files;
            var file;

            if (files && files.length) {
               file = files[0];

               if (/^image\/\w+$/.test(file.type)) {
                    blobURL = URL.createObjectURL(file);
                    $image.one('built.cropper', function () {
                        // Revoke when load complete
                       URL.revokeObjectURL(blobURL);
                    }).cropper('reset').cropper('replace', blobURL);
                    $inputImage.val('');
                } else {
                    window.alert('Please choose an image file.');
                }
            }

            // Amazi UI 上传文件显示代码
            var fileNames = '';
            $.each(this.files, function() {
                fileNames += '<span class="am-badge">' + this.name + '</span> ';
            });
            $('#file-list').html(fileNames);
        });
    } else {
        $inputImage.prop('disabled', true).parent().addClass('disabled');
    }
    
    //绑定上传事件
    $('#up-btn-ok').on('click',function() {
    	var $modal = $('#my-modal-loading');
    	var $modal_alert = $('#my-alert');
    	var img_src=$image.attr("src");

    	if(img_src==""){
    		set_alert_info("没有选择上传的图片");
    		$modal_alert.modal();
    		return false;
    	}
    	
    	$modal.modal();

    	var canvas=$("#image").cropper('getCroppedCanvas');
    	var data=canvas.toDataURL(); //转成base64
        data=data.split(',')[1];
        data=window.atob(data);
        var ia = new Uint8Array(data.length);
        for (var i = 0; i < data.length; i++) {
            ia[i] = data.charCodeAt(i);
        }
        var blob=new Blob([ia],{type:"image/png",endings:'transparent'});
        var fd=new FormData();
        fd.append('file',blob,'image.png');

        $modal_alert.modal();

        $("#doc-modal-1").modal('close');
        $.wdfProgress.progress("上传中...将自动刷新页面.",$("body", window.parent.parent.document));
        setTimeout("$(\"#undefined_wdfProgress_Bg\",window.parent.parent.document).hide()",1000);
        setTimeout("$(\"#undefined_wdfProgress_Prog\",window.parent.parent.document).hide()",1000);

        $.ajax( {
                url: basePath + "/filesManager/upload?serviceName=Main&isScale=true",
                //headers: {"Content-Type": "multipart/form-data;"},
                dataType:'json',
                type: "POST",
                processData : false,// 告诉jQuery不要去处理发送的数据
                contentType : false, // 告诉jQuery不要去设置Content-Type请求头
                async:false,
                data: fd,
                success: function(data){
                	$modal.modal('close');
                	if(data.status==1) {
                		// $("#up-img-touch img").attr("src",data.file);
                		// var img_name=data.file.split('/')[2];
                		// $("#pic").text(img_name);

                		AddUserHead(data.data.url);
                	}
                },
                error: function() {
                	$modal.modal('close');
                	set_alert_info("上传文件失败了！");
                	$modal_alert.modal();
                	//console.log('Upload error');  
                }

         });

        function AddUserHead(path) {
            var userId = $("#curUserId").val();
            $.ajax({
                type: "POST", //提交方式
                url: basePath+ "/user/updateHeaderPath",//路径
                data: {
                    "headerpath": path,
                    "id": userId
                },//数据，这里使用的是Json格式进行传输
                success: function (result) {//返回数据根据结果进行相应的处理
                    if (result.status = 1) {
                        //Referesh();
                        // set_alert_info("上传成功,将自动刷新页面");

                        $("#mainFrame").attr("src", basePath+"/dtt/main?url=imp/home/personal");

                    } else {
                        set_alert_info("'提交失败，请重试.....");
                        $modal_alert.modal();
                    }
                }
            });
        }

    });
    
});

function rotateimgright() {
    $("#image").cropper('rotate', 90);
}

function rotateimgleft() {
    $("#image").cropper('rotate', -90);
}

function set_alert_info(content){
	$("#alert_content").html(content);
}